(function () {
    function omesaasProduct(option) {
        if (!option.product || option.product instanceof Array) {
            return false;
        }

        this.product = option.product;

        this.optionLength = option.product.options.length;

        this.params = {
            quantity: 1,
            src: option.product.src,
            productTitle: option.product.title,
            product_id: option.product.id
        };

        this.attrOption = [];

        this.cartShake = true;

        this.buyShake = true;
        
        this.changeOption = option.changeOption;

        this.data_from = option.data_from || "";

        this.ec_currency_code = option.ec_currency_code || "";

        // this.handleRender = option.handleRender;
        this.variant = option.product.variants;

        this.renderOption = option.renderOption || true;

        // if (option.product.variant instanceof Array) {
        //     this.variant = option.product.variant;
        // } else {
        //     this.variant = option.product.variants;
        // }

        // 是否渲染规格
        if (this.renderOption) {
            this.formDom = $(option.id);

            this.numberNode = this.formDom.find(".product-price-number");

            this.marketNode = this.formDom.find(".product-price-market");

            this.skuNode = this.formDom.find(".sku-cell");

            const tempID = `#omesaas-product-sku-${themeConfig.global.product_option_type || "default"}`;
            this.skuTemplate = $(tempID).html();

            const self = this;
            this.skuNode.on("click", ".product-sku-values-item", function (params) {
                const item = $(this).data("value");
                const index = $(this).data("index");

                //是否库存空能否购买
                if (!self.isCurrentOptionBuy(item)) {
                    return false;
                }
                self.attrOption[index - 1].selected_value = item.value;
                for (let i = 0; i < self.optionLength; i++) {
                    self.attrOption[i].value = [];
                }
                self.setSkuOption();
            });

            this.skuNode.on("change", ".product-sku-unselect", function (params) {
                const item = $(this).find("option:selected").data("value");
                const index = $(this).find("option:selected").data("index");
                //是否库存空能否购买
                if (!self.isCurrentOptionBuy(item)) {
                    return false;
                }
                self.attrOption[index - 1].selected_value = item.value;
                for (let i = 0; i < self.optionLength; i++) {
                    self.attrOption[i].value = [];
                }
                self.setSkuOption();
            });
        }
        this.initSku();
    }

    omesaasProduct.prototype.initSku = function () {
        const self = this;
        const copyList = JSON.parse(JSON.stringify(this.variant));

        // var minPriceItem = copyList.sort((a, b) => a.price - b.price);
        //查询第一个满足库存不为0的数据
        let FirstPriceItemIndex = 0;
        if (this.product.inventory_policy !== 2 && this.product.inventory_tracking === 1) {
            FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);
        }
        // const FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);

        //多规款
        if (this.optionLength) {
            const selected = FirstPriceItemIndex === -1 ? false : this.isCurrentOptionBuy(copyList[FirstPriceItemIndex]);
            for (let i = 0; i < this.optionLength; i++) {
                this.attrOption.push({
                    name: "",
                    isImg: false,
                    selected_value: selected ? copyList[FirstPriceItemIndex][`option${i + 1}_value`] : "",
                    value: []
                });
            }
            this.setSkuOption();
        } else {
            this.setSelectedVal(copyList[0]);
            this.setPriceVal(copyList[0]);
        }
    };

    omesaasProduct.prototype.isCurrentOptionBuy = function (item) {
        // const quantity = item.quantity || item.inventory_quantity || 0;
        // if ((this.product.inventory_policy === 1 || this.product.inventory_policy === 3) && quantity === 0 && this.product.inventory_tracking === 1) {
        //     console.warn(this.product.inventory_policy);
        //     return false;
        // }
        return item.available ? true : false;
    };

    omesaasProduct.prototype.optionIndexKey = function (index) {
        return { title: `option${index + 1}_title`, value: `option${index + 1}_value_title`, id: `option${index + 1}_value` };
    };

    //获取可选项
    omesaasProduct.prototype.getOptional = function (sku) {
        for (let i = 0; i < sku.length; i++) {
            const element = sku[i];
            if (this.isCurrentOptionBuy(element)) {
                return element;
            }
        }
        return false;
    };

    omesaasProduct.prototype.setSkuOption = function () {
        let filterSKu = JSON.parse(JSON.stringify(this.variant));
        const product_sku_options = themeConfig.global.product_sku_options;
        let isSetOptionImg = false;

        this.attrOption.map((attr, i) => {
            const { title, value, id } = this.optionIndexKey(i);

            //设置当前选项卡是否需要显示图片
            for (let index = 0; index < filterSKu.length; index++) {
                const element = filterSKu[index];
                if (!attr.name) {
                    attr.name = element[title];
                    if (product_sku_options && product_sku_options.indexOf(attr.name) > -1 && !isSetOptionImg) {
                        attr.isImg = true;
                        isSetOptionImg = true;
                    }
                }

                const currentIndex = attr.value.findIndex((val) => val.name === element[value]);
                if (currentIndex > -1) {
                    attr.value[currentIndex].quantity += element.inventory_quantity;

                    if (!attr.value[currentIndex].available && element.available) {
                        attr.value[currentIndex].available = element.available;
                    }
                } else {
                    attr.value.push({
                        name: element[value],
                        value: element[id],
                        available: element.available,
                        image: element.image || "",
                        quantity: element.inventory_quantity
                    });
                }
            }

            //如果选择过滤选择的数据
            if (attr.selected_value) {
                const currentOption = attr.value.filter((el) => el.value === attr.selected_value);

                //如果没有匹配项；循环获取满足条件的第一条
                if (!currentOption.length) {
                    const option = this.getOptional(filterSKu);
                    attr.selected_value = option[id];
                }

                filterSKu = filterSKu.filter((el) => el[id] === attr.selected_value);

                //如果没有信息清空信息
                if (!filterSKu.length) {
                    attr.selected_value = "";
                    this.setSelectedVal(false);
                }

                if (i === this.attrOption.length - 1 && filterSKu.length === 1 && attr.selected_value) {
                    this.setSelectedVal(filterSKu[0]);
                    this.setPriceVal(filterSKu[0]);
                }
            }
            return attr;
        });
        // console.warn(this.attrOption)
        this.render();
    };

    //设置价格
    omesaasProduct.prototype.setPriceVal = function (currentSku) {

        if(this.renderOption){

            this.numberNode.html(formatMoney(currentSku.price, oemcart_currency));
            
            if (currentSku.compare_at_price > currentSku.price) {
                this.marketNode.html(formatMoney(currentSku.compare_at_price, oemcart_currency));
            } else {
                this.marketNode.html("");
            }
        }
    };

    //设置选中的val
    omesaasProduct.prototype.setSelectedVal = function (currentSku) {
        const product = this.product;
        const params = this.params;
        if (!currentSku) {
            this.params = {
                src: product.src,
                productTitle: product.title,
                product_id: product.id,
                sku_value: "",
                quantity: params.quantity || 1
            };
        } else {
            this.params = Object.assign(params, currentSku);

            //设置选中的sku
            if (this.optionLength) {
                let skuName = [];
                for (let i = 0; i < this.optionLength; i++) {
                    const title = this.params[`option${i + 1}_title`];
                    const value = this.params[`option${i + 1}_value_title`];
                    skuName.push(`${title}:${value}`);
                }
                this.params["sku_value"] = skuName.join("<br/>");
            }
        }

        this.changeOption && this.changeOption.call(this, this.params);
    };

    // 渲染页面
    omesaasProduct.prototype.render = function () {
        if(this.renderOption){
            const self = this;
            engine
            .parseAndRender(this.skuTemplate, {
                skus: this.attrOption,
                inventoryPolicy: this.product.inventory_policy,
                inventoryTracking: this.product.inventory_tracking
            })
            .then(function (liquidHtml) {
                // console.log(liquidHtml)
                self.skuNode.html(liquidHtml);
                window.addLazyImages && addLazyImages(self.skuNode.find("img[data-src]"));
            });
        }
    };

    //验证数据
    omesaasProduct.prototype.verifyOption = function (type) {
        //库存为0时不能购买
        if (this.product.available === 0) {
            moi.alertInfo({ content: "quantity empty" });
            return false;
        }

        if (type === "cart" && !this.cartShake) {
            return false;
        }

        if (type === "buy" && !this.buyShake) {
            return false;
        }
        for (let i = 0; i < this.attrOption.length; i++) {
            if (!this.attrOption[i].selected_value) {
                moi.tooltip({
                    el: this.skuNode.find(".product-sku-name").eq(i),
                    content: "select " + this.product.options[i].name
                });
                return false;
            }
        }
        return true;
    };

    //获取ec_data参数
    omesaasProduct.prototype.getEcData = function () {
        const self = this;
        return {
            ec_data_id: self.product.id,
            ec_data_from: self.data_from,
            ec_data_name: self.product.title,
            ec_data_price: self.params.price,
            ec_data_discount_price: self.params.price,
            ec_data_spu: self.product.spu,
            ec_data_image: self.product.src,
            ec_data_category: self.product.product_type,
            ec_data_uniq_id: self.product.id,
            ec_data_sku: self.params.sku,
            ec_data_sku_code: self.params.sku_code,
            ec_data_quantity: self.params.quantity,
            ec_data_sku_name: self.params.sku_value || "",
            ec_currency_code: self.ec_currency_code,
            ec_data_action_type: ""
        };
    };

    omesaasProduct.prototype.share = function (platform) {
        const self = this;
        const ec_data = {
            ec_data_id: self.product.id,
            ec_data_from: self.data_from,
            ec_data_name: self.product.title,
            ec_data_price: self.product.variant.price,
            ec_data_discount_price: self.product.variant.price,
            ec_data_spu: self.product.spu,
            ec_data_image: self.product.src,
            ec_data_category: self.product.product_type,
            ec_data_uniq_id: self.product.id,
            ec_data_sku: self.product.variant.sku,
            ec_data_sku_code: self.product.variant.sku_code,
            ec_data_quantity: 1,
            ec_data_sku_name: self.product.variant.sku_value,
            ec_currency_code: self.ec_currency_code,
            ec_data_action_type: ""
        };
        ec_data.ec_data_action_type = "share_product";
        callback_share_product(ec_data, platform);
    };

    //回调添加购物车
    omesaasProduct.prototype.callbackAddToCart = function () {
        const self = this;
        const ec_data = self.getEcData();
        ec_data.ec_data_action_type = "add_to_cart";
        callback_add_to_cart(ec_data);
    };

    //加入购物车
    omesaasProduct.prototype.addCart = function (complete, success) {
        const self = this;
        self.cartShake = false;
        moi.ajax({
            url: "/cart/add",
            type: "post",
            data: JSON.stringify({
                product_id: this.product.id,
                sku_code: this.params.sku_code,
                quantity: this.params.quantity,
                data_from: self.data_from
            }),
            complete() {
                self.cartShake = true;
                complete && complete.call(this);
            },
            success: function (data) {
                if (!data.code) {
                    if (window.callback_add_to_cart) {
                        self.callbackAddToCart();
                    }
                    miniCart();
                    const unm = parseInt($("#cart_number").text() || 0) + self.params.quantity;
                    $("#cart_number")
                        .show()
                        .html(unm > 99 ? 99 + "+" : unm);
                    self.setSelectedVal({ subtotalPrice: data.data.items_subtotal_price });
                }
                success && success.call(self, data);
            }
        });
    };

    //立即购买
    omesaasProduct.prototype.buynow = function (complete, success) {
        const self = this;
        self.buyShake = false;
        moi.ajax({
            url: "/cart/buynow",
            type: "post",
            data: JSON.stringify({
                product_id: this.product.id,
                sku_code: this.params.sku_code,
                quantity: this.params.quantity,
                data_from: self.data_from
            }),
            complete() {
                self.buyShake = true;
                complete && complete.call(this);
            },
            success: function (ret) {
                if (!ret.code && window.callback_add_to_cart) {
                    self.callbackAddToCart();
                }
                success && success.call(self, ret);
            }
        });
    };

    //购物车弹窗
    omesaasProduct.prototype.cartLayer = function () {
        const option = JSON.parse(JSON.stringify(this.params));
        const subtotalPrice = formatMoney(parseFloat(option.subtotalPrice || 0), oemcart_currency);
        const popupLayer = moi.popup();
        engine
            .parseAndRender($("#omesaas-popup-addPurchase-success").html(), {
                option: option,
                subtotalPrice: subtotalPrice,
                lang: window.lang
            })
            .then(function (html) {
                popupLayer.addContent(html);
                const temp = popupLayer.temp;
                //提交购物车跳转地址填写
                const submitNodes = temp.find(".cart-button");

                submitNodes.on("click", function () {
                    temp.find(".cart_form").submit();
                    popupLayer.close();
                });
            });
    };

    window.omesaasProduct = omesaasProduct;
})();
